﻿using EventNext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Chat
{
    [Service(typeof(IChatService))]
    public class ChatServer : ActorState, IChatService
    {
        ChatUser CurrentUser = null;
        readonly object locker = new object();
        static ulong count = 0;
        static readonly Task ticker = null;
        static ChatServer()
        {
            ticker = Task.Run(() =>
            {
                while(true)
                {
                    Thread.Sleep(5000);
                    Console.WriteLine($"现在处理了{count}次！");
                }
            });
        }

        public async Task<List<ChatUser>> GetOnlineUsers()
        {
            return await Task.Run<List<ChatUser>>(() =>
            {
                return ChatUser.OnlineUsers.ToList();
            });
        }

        public async Task Say(string message)
        {
            await Task.Run(() =>
            {
                CallContext.SetData("UserId", this.ActorID);
                ChatService.Say(message);
            }); 
            await ChatService.Say(message,this.ActorID);
        }

        public async Task SayTo(string message, ChatUser to)
        {
            await Task.Run(() =>
            {
                CallContext.SetData("UserId", this.ActorID);
                ChatService.SayTo(message,to);
            });
        }

        public async Task SignIn(string name)
        {
            await Task.Run(() =>
            {
                ChatUser user = new ChatUser(this.ActorID, name);
                CurrentUser = user;
                ChatUser.OnlineUsers.Add(user);
                Console.WriteLine($"{user} 进入聊天室");
            });
        }

        public async Task Perfermance(ChatUser to)
        {
            await Task.Run(() =>
            {
                count++;                
            });
        }

    }
}
